<script lang="ts" setup>
  import {
    computed,
    onBeforeMount,
    onBeforeUnmount,
    onMounted,
    ref,
  } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import dayjs from 'dayjs';
  import {
    Game,
    GameDetailSectionItem,
    GameRule,
    GameScheduleItem,
  } from '@/types/game';
  import { Form, Message, RequestOption } from '@arco-design/web-vue';
  import { uploadImage } from '@/api/common';
  import { CourseCup, CourseItem } from '@/types/course';
  import {
    GameGroupTypes,
    GamePayWays,
    GameRegionLevels,
    GameScoreTypes,
    GameTypes,
    RankLevels,
  } from '@/config/game';
  import ProvinceJSON from '@/config/province.json';
  import CityJSON from '@/config/city.json';
  import _ from 'lodash';
  import {
    createGame,
    getCourseList,
    getGameDetail,
    getGameList,
    publishGame,
    updateGame,
  } from '@/api/game';
  import { OperatorItem } from '@/types/operators';
  import { getOperatorList } from '@/api/operator';
  import { useAppStore } from '@/store';
  import DetailSectionInput from '@/views/game/editor/detail-section-input.vue';
  import CheckGroupBio from '@/components/check-group-bio.vue';
  import useTable from '@/hooks/table';
  import { getGameRuleList } from '@/api/game-rule';
  import scrollToFirstError from '@/utils/scroll-to-first-error';
  import GameProduct from './game-product.vue';
  import ProductEditor from './product-editor/index.vue';
  import GamePreview from './game-preview.vue';
  import ScheduleInput from './schedule-input.vue';

  const appStore = useAppStore();

  onBeforeMount(() => {
    appStore.updateSettings({
      menu: false,
    });
  });

  onBeforeUnmount(() => {
    appStore.updateSettings({
      menu: true,
    });
  });

  const router = useRouter();
  const route = useRoute();

  const data = ref<Partial<Game>>({});

  const goBack = () => {
    router.push({
      name: 'GameListApp',
    });
  };

  const sizeMap = {
    logo: 1024 * 1024,
    pics: 3 * 1024 * 1024,
    detailPics: 5 * 1024 * 1024,
  };

  const customUploadImage = (options: RequestOption) => {
    const { fileItem, onError, onSuccess, name } = options;

    const continueUpload = async () => {
      const fd = new FormData();
      fd.append('upload', fileItem.file as File);
      try {
        const res = await uploadImage(fd, new AbortController());
        onSuccess(res.data.data);
      } catch (err) {
        onError('上传失败');
      }
    };

    if (fileItem.file) {
      if (
        sizeMap[name as keyof typeof sizeMap] &&
        fileItem.file.size > sizeMap[name as keyof typeof sizeMap]
      ) {
        onError('图片尺寸过大');
        Message.error('图片尺寸过大');
      } else {
        const fileReader = new FileReader();
        fileReader.readAsDataURL(fileItem.file);
        fileReader.onload = () => {
          const img = new Image();
          img.src = fileReader.result as string;
          img.onload = () => {
            if (name === 'logo') {
              if (img.width !== img.height) {
                onError('图片比例不正确');
                Message.error('图片比例不正确');
              } else {
                continueUpload();
              }
            } else {
              continueUpload();
            }
          };
        };
      }
    }

    return {};
  };

  const saving = ref(false);
  const publishing = ref(false);
  const formRef = ref<InstanceType<typeof Form> | null>(null);

  const courseList = ref<CourseItem[]>([]);
  const cupList = ref<CourseCup[]>([]);
  const handleSearchCourse = async (value: string) => {
    try {
      const res = await getCourseList({
        pageIndex: 1,
        pageSize: 50,
        name: value,
        // 全部
        onlyForData: -1,
      });
      courseList.value = res.data.data.list || [];

      const course = courseList.value.find((i) => i.id === data.value.courseId);
      if (course) {
        data.value.course = course;
        cupList.value = course.courseCups || [];
      }
    } finally {
      // do nothing
    }
  };

  const handleCourseChanged = () => {
    const course = courseList.value.find((i) => i.id === data.value.courseId);
    if (course) {
      data.value.course = course;
      cupList.value = course.courseCups || [];
      if (cupList.value.length === 1) {
        data.value.cupId = cupList.value[0].id;
      } else {
        data.value.cupId = '';
      }

      if (
        data.value.logoFileList === undefined ||
        data.value.logoFileList.length === 0
      ) {
        data.value.logoFileList = [
          {
            status: 'done',
            uid: course.logo,
            url: course.logo,
            response: course.logo,
          },
        ];
      }
    }
  };

  const operatorList = ref<OperatorItem[]>([]);
  const handleSearchOperator = async (value: string) => {
    try {
      const res = await getOperatorList({
        pageIndex: 1,
        pageSize: 50,
        content: value,
      });
      operatorList.value = res.data.data.list || [];
    } finally {
      // do nothing
    }
  };

  const parentGameList = ref<Game[]>([]);
  const theParentGame = computed(() => {
    return parentGameList.value.find((i) => i.id === data.value.parentId);
  });
  const handleSearchParentName = async (content: string) => {
    const res = await getGameList({
      pageIndex: 1,
      pageSize: 30,
      gameType: 1,
      name: content,
    });
    parentGameList.value = res.data.data.list || [];
  };

  const { list: ruleList } = useTable<GameRule>();
  const initGameRules = async () => {
    try {
      const res = await getGameRuleList();
      ruleList.value = res?.data?.data || [];
    } finally {
      // do nothing
    }
  };

  const showDetailSection = ref(true);
  const handleRuleSelected = (id: number) => {
    const gameRule = ruleList.value.find((i) => i.id === id);
    if (gameRule) {
      showDetailSection.value = false;
      data.value.detailSectionList = JSON.parse(
        gameRule.ruleDetail
      ) as GameDetailSectionItem[];
      setTimeout(() => {
        showDetailSection.value = true;
      }, 100);
    }
  };

  const loadingDetail = ref(true);
  const initEditingGame = async () => {
    try {
      const gameRes = await getGameDetail(route.query.id as string);
      const theGame = gameRes.data.data;
      if (theGame) {
        if (!theGame.themeColor) {
          theGame.themeColor = '#17b978';
        }
        theGame.range = [
          dayjs(theGame.startDate).format('YYYY-MM-DD 00:00:00'),
          dayjs(theGame.endDate).format('YYYY-MM-DD 00:00:00'),
        ];
        theGame.signRange = [
          dayjs(theGame.signStartDate).format('YYYY-MM-DD HH:mm:ss'),
          dayjs(theGame.signEndDate).format('YYYY-MM-DD HH:mm:ss'),
        ];
        if (theGame.rmbPrice) {
          theGame.rmbPrice /= 100;
        }
        if (theGame.rmbDiscount) {
          theGame.rmbDiscount /= 100;
        }
        if (theGame.caddieFee) {
          theGame.caddieFee /= 100;
        }
        if (theGame.logo) {
          theGame.logoFileList = [
            {
              status: 'done',
              uid: theGame.logo,
              url: theGame.logo,
              response: theGame.logo,
            },
          ];
        }
        if (theGame.pics) {
          const pics = JSON.parse(theGame.pics || '[]') as string[];
          theGame.picsFileList = pics.map((i) => ({
            status: 'done',
            uid: i,
            url: i,
            response: i,
          }));
        }
        if (theGame.detailPics) {
          const pics = JSON.parse(theGame.detailPics || '[]') as string[];
          theGame.detailPicsFileList = pics.map((i) => ({
            status: 'done',
            uid: i,
            url: i,
            response: i,
          }));
        }
        if (theGame.signShareImage) {
          theGame.signShareImageFileList = [
            {
              status: 'done',
              uid: theGame.signShareImage,
              url: theGame.signShareImage,
              response: theGame.signShareImage,
            },
          ];
        }
        if (theGame.shareImage) {
          theGame.shareImageFileList = [
            {
              status: 'done',
              uid: theGame.shareImage,
              url: theGame.shareImage,
              response: theGame.shareImage,
            },
          ];
        }
        if (theGame.scheduleItems) {
          theGame.scheduleList = JSON.parse(
            theGame.scheduleItems
          ) as GameScheduleItem[];
        }
        if (theGame.detailSections) {
          theGame.detailSectionList = JSON.parse(
            theGame.detailSections
          ) as GameDetailSectionItem[];
        }
        if (theGame.gameProductGroupVOS) {
          theGame.gameProductGroupVOS.forEach((group) => {
            group.products.forEach((product) => {
              if (product.rmbPrice) {
                product.rmbPrice /= 100;
              }
            });
          });
        }
        data.value = theGame;
        handleSearchCourse(theGame.course?.name || '');
        handleSearchOperator(theGame.course?.name || '');
        handleSearchParentName(theGame.parentGame?.name || '');
      }
    } finally {
      loadingDetail.value = false;
    }
  };
  const isParentGame = computed(() => {
    return route.query.gameType === 'parent';
  });
  const isStageGame = computed(() => {
    return route.query.gameType === 'stage';
  });

  onMounted(() => {
    initGameRules();
    if (route.query.id) {
      initEditingGame();
    } else {
      data.value = {
        kickoffType: 1,
        payWay: 1,
        payMethod: 2,
        themeColor: '#17b978',
        scoreType: 31,
      };
      handleSearchCourse('');
      handleSearchOperator('');
      handleSearchParentName('');
      loadingDetail.value = false;
    }
  });

  const handleSubmit = async (approveState: number, testGame: number) => {
    if (formRef.value) {
      const validateResult = await formRef.value.validate();
      if (!validateResult) {
        try {
          const gameCloned = _.cloneDeep(data.value);
          if (gameCloned.range) {
            [gameCloned.startDate, gameCloned.endDate] = gameCloned.range;
            gameCloned.startDate = dayjs(gameCloned.startDate).format(
              'YYYY-MM-DD 00:00:00'
            );
            gameCloned.endDate = dayjs(gameCloned.endDate).format(
              'YYYY-MM-DD 23:59:59'
            );
            delete gameCloned.range;
          }
          if (
            gameCloned.logoFileList &&
            gameCloned.logoFileList[0]?.status === 'done'
          ) {
            gameCloned.logo = gameCloned.logoFileList[0]?.response;
            delete gameCloned.logoFileList;
          } else {
            Message.error('请上传比赛 Logo');
            return;
          }

          if (
            gameCloned.picsFileList &&
            gameCloned.picsFileList.filter((i) => i.status === 'done').length >
              0
          ) {
            gameCloned.pics = JSON.stringify(
              gameCloned.picsFileList
                .filter((i) => i.status === 'done')
                .map((i) => i.response)
            );
            delete gameCloned.picsFileList;
          } else {
            Message.error('请至少上传一张赛事宣传图');
            return;
          }

          if (
            gameCloned.detailPicsFileList &&
            gameCloned.detailPicsFileList.filter((i) => i.status === 'done')
              .length > 0
          ) {
            gameCloned.detailPics = JSON.stringify(
              gameCloned.detailPicsFileList
                .filter((i) => i.status === 'done')
                .map((i) => i.response)
            );
            delete gameCloned.detailPicsFileList;
          } else {
            if (isParentGame.value) {
              Message.error('请至少上传一张赛事宣传图');
              return;
            }
            gameCloned.detailPics = '[]';
          }

          if (
            gameCloned.signShareImageFileList &&
            gameCloned.signShareImageFileList.filter((i) => i.status === 'done')
              .length === 1
          ) {
            gameCloned.signShareImage =
              gameCloned.signShareImageFileList.filter(
                (i) => i.status === 'done'
              )[0].response;
            delete gameCloned.signShareImageFileList;
          } else {
            gameCloned.signShareImage = '';
          }

          if (
            gameCloned.shareImageFileList &&
            gameCloned.shareImageFileList.filter((i) => i.status === 'done')
              .length === 1
          ) {
            gameCloned.shareImage = gameCloned.shareImageFileList.filter(
              (i) => i.status === 'done'
            )[0].response;
            delete gameCloned.shareImageFileList;
          } else {
            gameCloned.shareImage = '';
          }

          if (gameCloned.rmbPrice) {
            gameCloned.rmbPrice *= 100;
          }
          if (gameCloned.rmbDiscount) {
            gameCloned.rmbDiscount *= 100;
          }
          if (gameCloned.caddieFee) {
            gameCloned.caddieFee *= 100;
          }

          if (gameCloned.signRange) {
            [gameCloned.signStartDate, gameCloned.signEndDate] =
              gameCloned.signRange;
            delete gameCloned.signRange;
          }

          const gameStartDate = dayjs(gameCloned.startDate);
          const signEndDate = dayjs(gameCloned.signEndDate);
          if (!signEndDate.isBefore(gameStartDate)) {
            Message.error('比赛时间要晚于报名时间');
            return;
          }

          if (gameCloned.scheduleList) {
            gameCloned.scheduleItems = JSON.stringify(gameCloned.scheduleList);
            delete gameCloned.scheduleList;
          }
          if (gameCloned.detailSectionList) {
            gameCloned.detailSections = JSON.stringify(
              gameCloned.detailSectionList
            );
            delete gameCloned.detailSectionList;
          }

          if (approveState === 0) {
            publishing.value = true;
          } else {
            saving.value = true;
          }
          gameCloned.testGame = testGame;

          if (isParentGame.value) {
            gameCloned.gameType = 1;
            gameCloned.childGameCount = 1;
            delete gameCloned.parentId;
          } else if (isStageGame.value) {
            gameCloned.gameType = 1;
            gameCloned.childGameCount = 2;
            delete gameCloned.parentId;
          } else if (gameCloned.parentId) {
            gameCloned.gameType = 2;
          } else {
            gameCloned.gameType = 0;
          }

          if (theParentGame.value?.childGameCount !== 2) {
            if ((gameCloned.gameProductGroupVOS || []).length === 0) {
              Message.error('请设置赛事费用');
              return;
            }
          }

          if (gameCloned.gameProductGroupVOS) {
            gameCloned.gameProductGroupVOS.forEach((group, groupIndex) => {
              group.sortNo = groupIndex;
              group.products.forEach((product, productIndex) => {
                product.sortNo = productIndex;
                if (product.rmbPrice) {
                  product.rmbPrice *= 100;
                }
              });
            });
          }

          if (gameCloned.gameType === 2 && gameCloned.payWay === 2) {
            Message.error('子比赛不支持线下支付');
            return;
          }

          const gameRes = route.query.id
            ? await updateGame(gameCloned)
            : await createGame(gameCloned);
          if (approveState === 0) {
            await publishGame(gameRes.data.data.id);
          }

          if (approveState === 0) {
            Message.success('赛事已发布');
          } else {
            Message.success('赛事已保存至草稿');
          }
          goBack();
        } finally {
          publishing.value = false;
          saving.value = false;
        }
      } else {
        scrollToFirstError(validateResult);
        Message.warning('信息填写有误，请检查');
      }
    }
  };
</script>

<template>
  <div class="wrapper" :class="{ parent: isParentGame }">
    <div class="main" :class="{ parent: isParentGame }">
      <div class="back">
        <a @click="goBack"><icon-arrow-left />返回</a>
      </div>
      <div class="title">
        {{ route.query.id ? '编辑' : '新建'
        }}{{
          isParentGame ? '父比赛' : isStageGame ? '多阶段赛事' : '普通赛事'
        }}
      </div>

      <a-skeleton v-if="loadingDetail" animation>
        <a-space direction="vertical" :style="{ width: '100%' }" size="large">
          <a-skeleton-line :rows="3" />
          <a-skeleton-shape />
        </a-space>
      </a-skeleton>
      <div v-else class="form">
        <a-form ref="formRef" :model="data" layout="vertical">
          <a-collapse
            :default-active-key="['basic', 'price', 'schedules', 'rules']"
          >
            <a-collapse-item key="basic" header="基本信息">
              <a-form-item
                label="赛事名称"
                field="name"
                :rules="[{ required: true, message: '不能为空' }]"
                style="width: 600px"
              >
                <a-input
                  v-model="data.name"
                  placeholder="请输入赛事名称，50个字以内"
                  :max-length="50"
                />
              </a-form-item>

              <a-form-item
                v-if="!isParentGame && !isStageGame"
                label="父赛事"
                field="parentId"
              >
                <a-select
                  v-model="data.parentId"
                  allow-clear
                  style="width: 600px"
                  allow-search
                  :disabled="!!data.id"
                  :options="
                    parentGameList.map((i) => ({
                      label: i.name,
                      value: i.id,
                    }))
                  "
                  @search="handleSearchParentName"
                />
              </a-form-item>

              <a-row :gutter="60">
                <a-col flex="none" style="width: 400px">
                  <a-form-item
                    label="最大可报名人数"
                    field="maxPlayerCount"
                    :rules="[{ required: true, message: '不能为空' }]"
                  >
                    <a-input-number
                      v-model="data.maxPlayerCount"
                      :min="1"
                      :precision="0"
                      :step="1"
                      hide-button
                    />
                  </a-form-item>
                </a-col>

                <a-col flex="none" style="width: 300px">
                  <a-form-item
                    label="教练是否可报名"
                    field="canTeacherSign"
                    :rules="[{ required: true, message: '不能为空' }]"
                  >
                    <a-radio-group
                      v-model="data.canTeacherSign"
                      :options="[
                        { label: '不可以报名', value: 0 },
                        { label: '可以报名', value: 1 },
                      ]"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-form-item
                label="报名时间"
                field="signRange"
                :rules="[{ required: true, message: '不能为空' }]"
              >
                <a-range-picker
                  v-model="data.signRange"
                  show-time
                  style="width: 400px"
                />
              </a-form-item>

              <a-form-item
                label="赛事日期"
                field="range"
                :rules="[{ required: true, message: '不能为空' }]"
              >
                <a-range-picker v-model="data.range" style="width: 400px" />
              </a-form-item>

              <template v-if="!isParentGame">
                <a-row :gutter="60">
                  <a-col flex="none" style="width: 400px">
                    <a-form-item
                      label="所在省份"
                      field="province"
                      :rules="[{ required: true, message: '不能为空' }]"
                    >
                      <a-select
                        v-model="data.province"
                        :options="
                          ProvinceJSON.map((i) => ({
                            label: i.name,
                            value: i.id,
                          }))
                        "
                        @change="data.city = undefined"
                      ></a-select>
                    </a-form-item>
                  </a-col>
                  <a-col flex="none" style="width: 400px">
                    <a-form-item
                      label="所在城市"
                      field="city"
                      :rules="[{ required: true, message: '不能为空' }]"
                    >
                      <a-select
                        v-model="data.city"
                        :options="
                      (CityJSON[data.province as keyof typeof CityJSON] || []).map((i) => ({ label: i.name, value: i.id }))
                    "
                      ></a-select>
                    </a-form-item>
                  </a-col>
                </a-row>

                <a-row :gutter="60">
                  <a-col flex="none" style="width: 400px">
                    <a-form-item
                      label="举办球场"
                      field="courseId"
                      :rules="[{ required: true, message: '不能为空' }]"
                    >
                      <a-select
                        v-model="data.courseId"
                        allow-search
                        placeholder="请选择举办球场"
                        style="width: 400px"
                        :options="
                          courseList.map((i) => ({
                            label: i.name,
                            value: i.id,
                          }))
                        "
                        @search="handleSearchCourse"
                        @change="handleCourseChanged"
                      ></a-select>
                    </a-form-item>
                  </a-col>
                  <a-col flex="none" style="width: 400px">
                    <a-form-item
                      label="举办场地"
                      field="cupId"
                      :rules="[{ required: true, message: '不能为空' }]"
                    >
                      <a-select
                        v-model="data.cupId"
                        allow-search
                        placeholder="请选择举办场地"
                        style="width: 400px"
                        :options="
                          cupList.map((i) => ({ label: i.name, value: i.id }))
                        "
                      ></a-select>
                    </a-form-item>
                  </a-col>
                </a-row>

                <a-form-item
                  label="承办执行机构"
                  field="operatorId"
                  :rules="[{ required: true, message: '不能为空' }]"
                >
                  <a-select
                    v-model="data.operatorId"
                    allow-search
                    placeholder="请选择承办执行机构"
                    style="width: 400px"
                    :options="
                      operatorList.map((i) => ({ label: i.name, value: i.id }))
                    "
                    @search="handleSearchOperator"
                  ></a-select>
                </a-form-item>
              </template>

              <template v-if="!isParentGame">
                <a-form-item
                  label="赛事积分级别"
                  field="rankLevel"
                  :rules="[{ required: true, message: '不能为空' }]"
                >
                  <a-radio-group
                    v-model="data.rankLevel"
                    :options="RankLevels"
                  />
                </a-form-item>

                <a-form-item
                  label="赛事级别"
                  field="regionLevel"
                  :rules="[{ required: true, message: '不能为空' }]"
                >
                  <a-radio-group
                    v-model="data.regionLevel"
                    :options="GameRegionLevels"
                  />
                </a-form-item>

                <a-form-item
                  label="赛事类型"
                  field="type"
                  :rules="[{ required: true, message: '不能为空' }]"
                >
                  <a-radio-group v-model="data.type" :options="GameTypes" />
                </a-form-item>

                <a-form-item
                  label="比赛形式"
                  field="groupType"
                  :rules="[{ required: true, message: '不能为空' }]"
                >
                  <CheckGroupBio
                    v-model="data.groupType"
                    :options="GameGroupTypes"
                  />
                </a-form-item>

                <a-form-item
                  label="开球方式"
                  field="kickoffType"
                  :rules="[{ required: true, message: '不能为空' }]"
                >
                  <a-radio-group
                    v-model="data.kickoffType"
                    :options="[
                      { label: '18洞同时开球', value: 1 },
                      { label: '按照Teetime发球', value: 2 },
                    ]"
                  />
                </a-form-item>

                <a-form-item
                  label="球童计分类型"
                  field="kickoffType"
                  :rules="[{ required: true, message: '不能为空' }]"
                >
                  <CheckGroupBio
                    v-model="data.scoreType"
                    :options="GameScoreTypes"
                  />
                </a-form-item>

                <a-form-item
                  field="kickoffTime"
                  :label="
                    data.kickoffType === 1 ? '开球时间' : '第一组开球时间'
                  "
                  :rules="[{ required: true, message: '不能为空' }]"
                >
                  <a-time-picker v-model="data.kickoffTime" format="HH:mm" />
                </a-form-item>

                <a-form-item
                  field="rewardTip"
                  label="奖励办法"
                  :rules="[{ required: true, message: '不能为空' }]"
                >
                  <a-input v-model="data.rewardTip" style="width: 400px" />
                </a-form-item>

                <a-form-item field="sponsors" label="赞助商">
                  <a-input v-model="data.sponsors" style="width: 600px" />
                </a-form-item>
              </template>

              <a-form-item
                label="赛事 Logo"
                field="logoFileList"
                :rules="[{ required: true, message: '请上传赛事Logo' }]"
              >
                <a-upload
                  v-model:file-list="data.logoFileList"
                  list-type="picture-card"
                  image-preview
                  name="logo"
                  :custom-request="customUploadImage"
                  :limit="1"
                />
                <template #extra>
                  请上传长宽比为1:1的图片，不大于1MB，建议尺寸160x160
                </template>
              </a-form-item>

              <a-form-item
                label="赛事宣传图"
                field="picsFileList"
                :rules="[{ required: true, message: '请上传赛事宣传图' }]"
              >
                <a-upload
                  v-model:file-list="data.picsFileList"
                  list-type="picture-card"
                  image-preview
                  name="pics"
                  :custom-request="customUploadImage"
                  :limit="10"
                />
                <template #extra>
                  建议上传长宽比为5:3的图片，每张图片不大于3MB，可上传多张
                </template>
              </a-form-item>

              <a-form-item
                label="赛事详情图"
                field="detailPicsFileList"
                :rules="
                  isParentGame
                    ? [{ required: true, message: '请上传赛事宣传图' }]
                    : []
                "
              >
                <a-upload
                  v-model:file-list="data.detailPicsFileList"
                  list-type="picture-card"
                  image-preview
                  name="detailPics"
                  :custom-request="customUploadImage"
                  :limit="10"
                />
                <template #extra> 每张图片不大于5MB，可上传多张 </template>
              </a-form-item>

              <a-form-item label="小程序分享图" field="shareImageFileList">
                <a-upload
                  v-model:file-list="data.shareImageFileList"
                  list-type="picture-card"
                  image-preview
                  name="shareImageFileList"
                  :custom-request="customUploadImage"
                  :limit="10"
                />
                <template #extra>
                  如果不上传，会默认使用第一张赛事宣传图
                </template>
              </a-form-item>

              <a-form-item
                label="报名成功分享图"
                field="signShareImageFileList"
              >
                <a-upload
                  v-model:file-list="data.signShareImageFileList"
                  list-type="picture-card"
                  image-preview
                  name="signShareImageFileList"
                  :custom-request="customUploadImage"
                  :limit="10"
                />
                <template #extra>
                  只有上传了图片，报名后才会弹出分享海报
                </template>
              </a-form-item>

              <a-form-item label="报名成功分享图底色" field="signShareColor">
                <a-input
                  v-model="data.signShareColor"
                  placeholder="请输入HEX格式的颜色值，如#ff00ff"
                />
              </a-form-item>
            </a-collapse-item>

            <a-collapse-item
              v-if="theParentGame?.childGameCount !== 2"
              key="price"
              header="赛事费用"
            >
              <template #extra>
                <a-popover position="bottom">
                  <a-button @click.stop>下单页预览</a-button>
                  <template #content>
                    <div style="color: var(--color-text-1); width: 375px">
                      <GameProduct
                        :parent-id="data.parentId"
                        :group-list="data.gameProductGroupVOS || []"
                      />
                    </div>
                  </template>
                </a-popover>
              </template>
              <a-form-item
                v-if="!isParentGame"
                label="支付手段"
                field="payWay"
                :rules="[{ required: true, message: '不能为空' }]"
              >
                <a-radio-group
                  v-model="data.payWay"
                  :options="GamePayWays"
                ></a-radio-group>
              </a-form-item>

              <ProductEditor
                v-model="data.gameProductGroupVOS"
                :is-child-game="!!data.parentId"
              />

              <!--              <a-form-item-->
              <!--                label="支付方式"-->
              <!--                field="payMethod"-->
              <!--                :rules="[{ required: true, message: '不能为空' }]"-->
              <!--              >-->
              <!--                <a-radio-group-->
              <!--                  v-model="data.payMethod"-->
              <!--                  :options="GamePayMethods"-->
              <!--                ></a-radio-group>-->
              <!--              </a-form-item>-->

              <!--              <a-form-item-->
              <!--                v-if="data.payMethod === 1 || data.payMethod === 3"-->
              <!--                label="所需点数"-->
              <!--                field="pointPrice"-->
              <!--                :rules="[{ required: true, message: '不能为空' }]"-->
              <!--              >-->
              <!--                <a-input-number-->
              <!--                  v-model="data.pointPrice"-->
              <!--                  :min="1"-->
              <!--                  :precision="0"-->
              <!--                  :step="1"-->
              <!--                  hide-button-->
              <!--                  style="width: 300px"-->
              <!--                />-->
              <!--              </a-form-item>-->

              <!--              <a-form-item-->
              <!--                v-if="data.payMethod === 2 || data.payMethod === 3"-->
              <!--                :label="isParentGame ? '早鸟价' : '参赛费用'"-->
              <!--                field="rmbPrice"-->
              <!--                :rules="[{ required: true, message: '不能为空' }]"-->
              <!--              >-->
              <!--                <a-input-number-->
              <!--                  v-model="data.rmbPrice"-->
              <!--                  :min="0.01"-->
              <!--                  :precision="2"-->
              <!--                  hide-button-->
              <!--                  style="width: 300px"-->
              <!--                >-->
              <!--                  <template #prefix>￥</template>-->
              <!--                </a-input-number>-->
              <!--              </a-form-item>-->

              <!--              <a-form-item-->
              <!--                v-if="isParentGame"-->
              <!--                label="费用抵扣"-->
              <!--                field="rmbDiscount"-->
              <!--                :rules="[{ required: true, message: '不能为空' }]"-->
              <!--              >-->
              <!--                <a-input-number-->
              <!--                  v-model="data.rmbDiscount"-->
              <!--                  :min="0.01"-->
              <!--                  :precision="2"-->
              <!--                  hide-button-->
              <!--                  style="width: 300px"-->
              <!--                >-->
              <!--                  <template #prefix>￥</template>-->
              <!--                </a-input-number>-->
              <!--              </a-form-item>-->

              <!--              <div style="width: 340px">-->
              <!--                <a-form-item-->
              <!--                  label="费用包括"-->
              <!--                  field="payItems"-->
              <!--                  :rules="[{ required: true, message: '不能为空' }]"-->
              <!--                >-->
              <!--                  <MultiInput-->
              <!--                    v-model="data.payItems"-->
              <!--                    :options="['赛事服务费', '保险', '练习场免费球', '水补给']"-->
              <!--                  />-->
              <!--                </a-form-item>-->
              <!--              </div>-->

              <template v-if="!isParentGame">
                <a-form-item
                  label="赛事助理（球童）服务费"
                  field="caddieFee"
                  :rules="[{ required: true, message: '不能为空' }]"
                >
                  <a-input-number
                    v-model="data.caddieFee"
                    :min="0"
                    :precision="2"
                    hide-button
                    style="width: 300px"
                  >
                    <template #prefix>￥</template>
                  </a-input-number>
                </a-form-item>
                <a-form-item
                  label="赛事助理（球童）服务费说明"
                  field="caddieTip"
                >
                  <a-input v-model="data.caddieTip" style="width: 300px">
                  </a-input>
                </a-form-item>
              </template>
            </a-collapse-item>

            <template v-if="!isParentGame">
              <a-collapse-item key="schedules" header="赛事日程">
                <ScheduleInput v-model="data.scheduleList" />
              </a-collapse-item>

              <a-collapse-item key="rules" header="赛事规程">
                <template #extra>
                  <div @click.stop>
                    <a-select
                      placeholder="从模板选择"
                      style="width: 200px"
                      :options="
                        ruleList.map((i) => ({
                          label: i.ruleTitle,
                          value: i.id,
                        }))
                      "
                      @change="handleRuleSelected($event as number)"
                    ></a-select>
                  </div>
                </template>
                <DetailSectionInput
                  v-if="showDetailSection"
                  v-model="data.detailSectionList"
                />
              </a-collapse-item>
            </template>
          </a-collapse>
        </a-form>
      </div>

      <div class="footer">
        <a-space>
          <a-button
            :loading="saving"
            :disabled="publishing"
            @click="handleSubmit(-1, 0)"
          >
            保存为草稿
          </a-button>
          <a-button
            :loading="publishing"
            :disabled="saving"
            type="primary"
            @click="handleSubmit(0, 0)"
          >
            立即发布
          </a-button>
          <a-button
            v-if="!isParentGame"
            :loading="publishing"
            :disabled="saving"
            type="primary"
            @click="handleSubmit(0, 1)"
          >
            创建测试赛
          </a-button>
        </a-space>
      </div>
    </div>
    <div v-if="!isParentGame" class="preview">
      <div class="preview-title">小程序预览</div>
      <div class="preview-content">
        <div class="preview-status-bar">
          <div class="preview-status-icon"><icon-wifi /></div>
          <div class="preview-status-time">18:00</div>
          <div class="preview-status-capsule">
            <span class="capsule-menu"></span>
            <span class="capsule-close"></span>
          </div>
        </div>
        <div class="preview-content-main">
          <GamePreview :game="data" />
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
  .wrapper {
    width: 1440px;
    margin: 0 auto;
    display: flex;
    height: 100vh;
    &.parent {
      height: auto;
    }
  }
  .main {
    width: 1000px;
    padding: 20px;
    background: #fff;
    overflow: auto;
    &.parent {
      margin: 0 auto;
    }
  }
  .preview {
    margin-left: 30px;
    flex: 1;
    background: #fff;
    overflow: auto;
    &-title {
      line-height: 50px;
      padding: 0 20px;
      border-bottom: 1px solid var(--color-border-2);
      font-weight: 600;
    }
    &-content {
      background: #f5f5f5;
      width: 375px;
      margin: 20px auto;
      border: 1px solid var(--color-border-1);
      position: relative;
    }
    &-status-bar {
      position: absolute;
      left: 0;
      right: 0;
    }
    &-status-icon {
      position: absolute;
      left: 4px;
      top: 4px;
      color: #fff;
    }
    &-status-time {
      position: absolute;
      left: 50%;
      top: 4px;
      width: 100px;
      margin-left: -50px;
      text-align: center;
      color: #fff;
    }
    &-status-capsule {
      display: flex;
      align-items: center;
      padding: 0 10px;
      border: 1px solid #eee;
      position: absolute;
      right: 5px;
      top: 20px;
      background: #fff;
      height: 32px;
      border-radius: 16px;
      .capsule-menu {
        display: inline-block;
        width: 22px;
        height: 7px;
        mask: url('')
          50% 50% / cover no-repeat;
        background-color: #000;
        margin-right: 10px;
      }
      .capsule-close {
        display: inline-block;
        width: 17px;
        height: 17px;
        mask: url('')
          50% 50% / cover no-repeat;
        background-color: #000;
        margin-left: 5px;
      }
    }
  }

  .back {
    margin-bottom: 20px;
    display: inline-flex;
    align-items: center;
    cursor: pointer;
    color: var(--color-text-2);
    &:hover {
      color: rgb(var(--primary-6));
    }
  }

  .title {
    font-size: 20px;
    font-weight: 500;
  }

  .form {
    margin: 30px 0;

    :global(.arco-collapse-item-content) {
      background: #fff;
    }
  }

  .footer {
    margin: 30px 0 50px;
    text-align: center;
  }
</style>
